<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Covers all ajax methods used
 *
 * @package     VisualQ Local System
 * @author      CSU OJT Students '10 - '11 (Michael Roland B. Martin)
 * @copyright   Copyright (c) 2010 - 2011, Bitstop Network Services, Inc.
 * @version     1.0 January 27, 2011
 */

class Ajax extends Controller {

    function Ajax()
    {
        parent::Controller();

        // Load necessary library, helper and model files
        $this->load->model('ajax_model');

        // Load profiler, for TESTING / DEBUG only.
        //$this->output->enable_profiler(TRUE);
    }

    /**
     * Logout the agent widget
     *
     * Used by:
     *      agent_widget_view
     */
    function logout_widget()
    {
        // Load necessary library, helper and model files
        $this->load->helper('date');
        if( ! $this->session->userdata('id'))
        {
            redirect(base_url() . 'login/');
        }
        // Logout DTR
        $dtr = array(
            'account_id'    => $this->session->userdata('id'),
            'action'        => 1,
            'time'          => now()
        );
        $this->db->insert('dtr', $dtr);

        // Remove account session
        $data = array(
            'id'            => '',
            'account_type'  => ''
        );
        $this->session->unset_userdata($data);
    }

    /**
     * Fills the flexigrid with agent data
     *
     * Used by:
     *      js/front_desk.js
     */
    function new_queue_number()
    {
        // Load necessary library, helper and model files
        $this->load->model('statistics_model');

        // Get post data
        $params = array(
            'si' => $this->input->post('service_id'),
            'mn' => $this->input->post('mobile_number')
        );

        // Get a new queue number
        $result = $this->ajax_model->new_queue_number($params);

        // Increment the service count
        $this->statistics_model->increment_service($params['si']);

        echo $result;
    }

    /**
     * Get a queue number
     *
     * Used by:
     *      js/agent_widget.js
     */
    function get_queue_number()
    {
        // Check if there is an active queue number
        $result = $this->ajax_model->get_queue_number(TRUE);
        if($result->num_rows() > 0)
        {
            // Return the active queue number
            echo json_encode($result->row_array());
        }
        else
        {
            // Check if there is a waiting queue number
            $result = $this->ajax_model->get_queue_number(FALSE);

            if($result->num_rows() > 0)
            {
                $row = $result->row_array();

                // Set that waiting queue number to active
                $this->ajax_model->set_active($row['log_id']);

                // Return the active queue number
                echo json_encode($row);
            }
        }
    }

    /**
     * Set the missed number to active
     *
     * Used by:
     *      ajax/logs_grid/waiting
     */
    function serve_missed($li)
    {
        $this->ajax_model->serve_missed($li);
    }

    /**
     * Get the latest queue number per service
     *
     * Used by:
     *      view/display_view.php
     */
    function get_latest_numbers()
    {
        // Load necessary library, helper and model files
        $this->load->model('service_model');

        // Get all services that can be rendered by an agent
        $result = $this->service_model->get_available_services();

        foreach($result->result_array() as $row)
        {
            // Get the latest assigned queue number for the service
            $result = $this->ajax_model->get_latest_number($row['id']);

            // If there is a queue number
            if($result->num_rows() > 0)
            {
                $service = $result->row_array();
                $data['queue_number'][] = $row['prefix'] . $service['queue_number'];
                $data['counter'][] = $service['unit_name'];
            }
            else
            {
                $data['queue_number'][] = 'N/A';
                $data['counter'][] = '...';
            }
        }

        echo json_encode($data);
    }

    /**
     * Check if the mobile number matchs the queue number
     *
     * Used by:
     *      js/agent_widget.js
     *
     * @return  bool
     *      valid       :   mobile number matches the queue number
     */
    function confirm_mobile_number()
    {
        // Get post data
        $params = array(
            'li' => $this->input->post('log_id'),
            'mn' => $this->input->post('mobile_number')
        );

        // Check if the params match
        $result = $this->ajax_model->confirm_mobile_number($params);

        if($result->num_rows() > 0)
        {
            $row = $result->row_array();

            // If the mobile number and the queue number matches, start the service
            $this->ajax_model->start_service($row['id']);

            $valid = TRUE;
        }
        else
        {
            $valid = FALSE;
        }

        echo $valid;
    }

    /**
     * Set the queue number as missed and increments the miss count
     *
     * Used by:
     *      js/agent_widget.js
     */
    function skip_queue_number()
    {
        // Load necessary library, helper and model files
        $this->load->model('statistics_model');

        // Set the queue number as missed
        $this->ajax_model->skip_queue_number($this->input->post('log_id'));

        // Increment the miss count
        $this->statistics_model->increment_missed();
    }

    /**
     * Get the closing codes of a service
     *
     * Used by:
     *      js/agent_widget.js
     *
     * @return  string
     *      options     :   option tags for the closing codes, format <option value="CC">CC</option>[...]
     */
    function get_closing_codes()
    {
        // Load necessary library, helper and model files
        $this->load->model('service_model');

        $options = '';

        // Get the service details
        $result = $this->service_model->get_service_details($this->input->post('service_id'));
        if($result->num_rows() > 0)
        {
            $row = $result->row_array();

            // Separate closing codes
            $closing_codes = json_decode($row['closing_codes']);

            // Build option tags for the closing codes
            foreach($closing_codes as $value)
            {
                $options .= '<option value="' . $value . '">' . $value . '</option>';
            }
        }
        echo $options;
    }

    /**
     * Set the closing code and end time for the queue number
     *
     * Used by:
     *      js/agent_widget.js
     */
    function end_service()
    {
        // Load necessary library, helper and model files
        $this->load->model('statistics_model');

        // Get post data
        $params = array(
            'li' => $this->input->post('log_id'),
            'cc' => $this->input->post('closing_code')
        );

        // Set the closing code and end time
        $result = $this->ajax_model->end_service($params);

        $params['si'] = $result['si'];

        // Increment served count
        $this->statistics_model->increment_served($result['pt']);

        // Increment closing code count
        $this->statistics_model->increment_closing_code($params);
    }

    /**
     * Get the latest agent statistics
     *
     * Used by:
     *      agent_widget.js
     */
    function get_agent_stats()
    {
        // Get the statistics
        $result = $this->ajax_model->get_agent_stats();

        echo json_encode($result);
    }

    /**
     * Fills the flexigrid with agent data
     *
     * NOTE: The method is based on the codeigniter implementation prototype
     *
     * Used by:
     *      manager/agents_grid/
     */
    function agents_grid()
    {
        // Load necessary library, helper and model files
        $this->load->library('flexigrid');
        $this->load->helper('date');
        $this->load->model('service_model');

        // Set pop-up attributes
        $atts = array(
          'width'      => '320',
          'height'     => '400',
          'scrollbars' => 'yes',
          'status'     => 'yes',
          'resizable'  => 'yes',
          'screenx'    => '0',
          'screeny'    => '0'
        );

        // List of all fields that can be sortable. This is Optional.
        // This prevents that a user sorts by a column that we dont want him to access, or that doesnt exist, preventing errors.
        $valid_fields = array('id', 'last_name', 'first_name');
        $this->flexigrid->validate_post('id', 'asc', $valid_fields);

        // Get agent data
        $records = $this->ajax_model->agents_grid();

        foreach($records['records']->result() as $row)
        {
            // Get agent services
            $result = $this->service_model->get_agent_services($row->id);

            // Build services string
            if($result->num_rows > 0)
            {
                $rows = $result->result_array();
                $services = '';
                for($i = 0; $i < $result->num_rows(); $i++)
                {
                    if($i != 0)
                    {
                        $services .= ', ';
                    }
                    $services .= $rows[$i]['title'];
                }
            }

            // Build flexigrid row array
            $record_items[] = array(
                $row->id,
                $row->id,
                $row->last_name,
                $row->first_name,
                $services,
                anchor_popup('manager/account_info/' . $row->id, img('images/information.png'), $atts)
            );
        }

        // Print
        $this->output->set_header($this->config->item('json_header'));
        $this->output->set_output($this->flexigrid->json_build($records['record_count'], $record_items));
    }

    /**
     * Fills the flexigrid with logs data
     *
     * NOTE: The method is based on the codeigniter implementation prototype
     *
     * Used by:
     *      agent/logs_grid/
     *
     * @params  string
     *      type            :   what type of logs to be shown (waiting, served or missed)
     */
    function logs_grid($type = 'waiting')
    {
        // Load necessary library, helper and model files
        $this->load->library('flexigrid');
        $this->load->helper('date');

        // List of all fields that can be sortable. This is Optional.
        // This prevents that a user sorts by a column that we dont want him to access, or that doesnt exist, preventing errors.
        $valid_fields = array('id','service', 'issue_time','queue_number');
        // If the type is 'served', then add the following to the valid fields
        if(strcmp($type, 'served') == 0)
        {
            $valid_fields[] = array('timestart', 'timeend', 'processing_time', 'code');
        }
        $this->flexigrid->validate_post('id', 'asc', $valid_fields);

        // Get logs data
        $records = $this->ajax_model->logs_grid($type);
        $row_number = 0;
        foreach($records['records']->result() as $row)
        {
            $record_items[] = array(
                $row->id,
                $row->id,
                $row->title,
                mdate('%Y-%m-%d %H:%i:%s', $row->issue_time),
                $row->queue_number
            );
            if(strcmp($type, 'served') == 0)
            {
                array_push($record_items[$row_number], mdate('%Y-%m-%d %H:%i:%s', $row->timestart), mdate('%Y-%m-%d %H:%i:%s', $row->timeend), mdate('%H:%i:%s', $row->processing_time), $row->closing_code);
            }
            if(strcmp($type, 'missed') == 0)
            {
                array_push($record_items[$row_number], '<a href="#" onClick="$.post(\'' . base_url() . 'ajax/serve_missed/' . $row->id . '\'); opener.get_number = 1; window.close();">Serve</a>');
            }
            $row_number++;
        }

        // Print
        $this->output->set_header($this->config->item('json_header'));
        $this->output->set_output($this->flexigrid->json_build($records['record_count'],$record_items));
    }

}

/* End of file ajax.php */
/* Location: ./system/application/controllers/ajax.php */